<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\Auth;
use app\mill\model\Client as ClientModel;
use app\mill\model\Give as GiveModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Plan as PlanModel;
use app\admin\model\Config as ConfigModel;
use app\mill\model\Log as LogModel;
use think\Db;

/**
 * 排产计划单控制器
 * @package app\admin\controller
 */
class Plan extends Admin
{
    /**
     * 工程列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        //工艺
        $give_status = '';
        //时间
        $plan_time_arr = [];
        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        //$map[] = ['p.give_status','=','-1'];
        if (!empty($map)) {
            foreach ($map as $k => $v) {
                if ($v[0] == 'p.give_status') $give_status = $v[2];
                elseif ($v[0] == 'p.plan_time') {
                    //时间筛选，显示之前未完成的计划
                    $plan_time_arr = $v;
                    unset($map[$k]);
                };
            }
        }
        if(!empty($plan_time_arr)){
            $plan_time[0] = strtotime($plan_time_arr[2][0]);
            $plan_time[1] = strtotime($plan_time_arr[2][1]);
            $map2 = " (p.plan_time between {$plan_time[0]} and $plan_time[1] or (p.plan_time < {$plan_time[0]} and p.status = 0))";
            //$map[] = ['p.give_status','=','-1'];
        }
        // 数据列表
        $data_list = Db::name('mill_order_plan')
            ->alias('p')
            ->field("p.*,'{$give_status}' as give_status_map,o.engineering,o.batch,o.archives_bill_time")
            ->where($map)
            ->where($map2)
            ->leftJoin('mill_order o', 'o.id=p.order_id')
            ->group('p.order_id')
            ->order('p.plan_time desc,o.archives_bill_time desc')
            ->paginate()
            ->each(function ($v) {

                //接单后，3天内未开始生产则预警
                $give_where = [
                    ['order_id','=',$v['order_id']],
                    ['status','<>',0],
                ];
                $give_time = Db::name('mill_order_archives_give')->where($give_where)->order('status1_time asc')->value('status1_time');
                if(empty($give_time))$give_time = time();
                $give_time_out = ($give_time - $v['plan_time'])/86400;
                if($give_time_out > 3) $v["archives_sn"] .= '<br>' . OrderModel::status_tag(-1, '超3天未生产');

                //各生产状态计划单
                $plan_list_where = [['order_id','=',$v['order_id']],['give_status','>',-1]];
                if(!empty($v['give_status_map']))$plan_list_where[] = ['give_status','=',$v['give_status_map']];
                $plan_list = Db::name('mill_order_plan')->where($plan_list_where)->order('give_status asc')->select();

                if(!empty($plan_list)){
                    foreach ($plan_list as $gk => $plan) {
                        $gk = $plan['give_status'];
                        if(empty($plan['is_true'])){
                            $v["note{$gk}"] = OrderModel::status_tag(-1, '不安排计划');
                            continue;
                        }
                        $v["plan_time{$gk}"] = $plan['plan_time'];
                        $v["start_time{$gk}"] = $plan['start_time'];
                        $v["end_time{$gk}"] = $plan['end_time'];
                        $v["note{$gk}"] = '<div style="color: #ff6b6b;">' . $plan['note'] . '</div>';
                        $v["is_timeout{$gk}"] = $plan['is_timeout'];
                        $v["status{$gk}"] = $plan['status'];

                        //设置生产计划单后，3天内未开始生产则预警
                        if(!empty($plan['plan_time']) && empty($plan['start_time'])){
                            $plan['is_timeout2'] = (time() - $plan['plan_time'])/86400;
                            if($plan['is_timeout2'] > 3)$v["note{$gk}"] .= '<br>' . OrderModel::status_tag(-1, '超3天未生产');
                        }

                        if (isset($plan['is_timeout']) && $plan['is_timeout'] == 0) $v["note{$gk}"] .= '<br>' . OrderModel::status_tag(-1, '已超时');

                    }
                }


                return $v;
            });

        //排版表头
        $addColumns = [['archives_sn', ''],['engineering', ''],['batch', ''],];
        $table_head_html = '<th colspan="1">档案号</th><th colspan="1">项目名称</th><th colspan="1">批次</th>';

        //获取计划环节
        $sort = PlanModel::getPlanSort();
        $i = 1;
        foreach ($sort as $sk=>$sv){

            if(is_numeric($give_status) && $sk != $give_status)continue;

            $addColumns[] = ["plan_time{$sk}", '计划时间', 'date'];
            $addColumns[] = ["end_time{$sk}", '完成时间', 'date'];
            $addColumns[] = ["note{$sk}", '备注'];

            $table_head_html .= '<th colspan="3">工序'.$i.'：'.$sv.'</th>';

            $i++;
        }
        $table_head_html .= '<th colspan="1">操作</th>';
        $addColumns[] = ['right_button', '', 'btn'];

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    var wrapper_height = $("#builder-table-wrapper").css("max-height");
                    wrapper_height = parseInt(wrapper_height) + 30;
                    $("#builder-table-wrapper").css("max-height",wrapper_height+"px");
                    var table_head_html = \'<tr>\' +
                        \''.$table_head_html.'\'
                        + \'</tr>\';
                    $("#builder-table-head table thead").html(table_head_html+$("#builder-table-head table thead").html());
                    //固定右侧
                    $("#builder-table-right-head table thead").html(table_head_html+$("#builder-table-right-head table thead").html());
                    $("#builder-table-right-body").css("margin-top","100px");
                    var right_height = $("#builder-table-right").css("height");
                    right_height = parseInt(right_height) + 50;
                    $("#builder-table-right").css("height",right_height+"px");
                    
                    //固定左侧
                    $("#builder-table-left-head table thead").html(table_head_html+$("#builder-table-left-head table thead").html());
                    var left_height = $("#builder-table-left").css("height");
                    left_height = parseInt(left_height) + 50;
                    $("#builder-table-left").css("height",left_height+"px");
                            
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "生产计划单",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('生产计划单')// 页面标题
            ->setTableName('mill_order_plan')// 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:2', 'p.give_status', '工艺', '', '', $sort],
                ['text:2', 'o.order_sn', '工程编号', 'like'],
                ['select:2', 'o.client_id', '客户公司', '', '', $company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'p.plan_time', '日期'],
            ])
            ->addColumns($addColumns)
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->fixedLeft(3)
            ->fixedRight(1)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-default quality-print'])
            ->addTopButtons('add')// 批量添加顶部按钮
            ->addRightButton('add',['title' => '修改','href' => url('add',['order_id' => '__order_id__']),'class'=>'btn btn-default','icon'=>''])
            ->setRowList($data_list)// 设置表格数据
            ->setColumnWidth([
                'id' => 60,
                'archives_sn' => 120,
                'note' => 100,
                'mobile' => 100,
                'engineering' => 150,
                'money_str' => 60,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        $order_id = input('order_id');
        //获取发货部的产品状态
        $address_role = GiveModel::$role[8];
        $address_status = $address_role['status'][0];
        //生产工艺最后一个流程，发货前
        $last_give_status = $address_role['status'][1];

        if ($this->request->isPost()) {
            $data = input();
            $plan_list = $data['plan_list'];

            if (empty($data['order_id'])) $this->error('请选择工程');

            //工程信息
            $order = Db::name('mill_order')->where(['id' => $data['order_id']])->find();

            //选择的工艺
            $give_sort = [];

            foreach ($plan_list as &$v){

                //是否取消该工艺的排产计划
                $order['is_true'] = empty($v['is_true'])?0:$v['is_true'];

                $order['plan_title'] = $v['title'];
                $v['plan_time'] = strtotime($v['plan_time'])?strtotime($v['plan_time']):$v['plan_time'];

                PlanModel::updatePlan($order,$v['give_status'],$v['plan_time'],0,0,$v['note']);

                //组合选择的排产工艺
                if(!empty($v['is_true']) && $v['give_status'] > 0)$give_sort[] = $v['give_status'];
            }

            sort($give_sort);
            Db::name('mill_order')->where(['id' => $data['order_id']])->update(['give_sort'=>implode(',',$give_sort)]);

            $this->success('操作成功', url('index'));
        }

        //获取待生产的工程
        $order_list = [];
        $contract_time_list = [];
        $order_list_old = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,p.address_time')
            ->leftJoin('mill_order_place p','p.order_sn_off=o.order_sn_off')
            ->where("o.status=1 and o.give_status<{$last_give_status}")
            ->select();
            //->column("concat(archives_sn,'  ',engineering) as str_name", 'id');
        if(!empty($order_list_old)){
            foreach ($order_list_old as $v){
                $order_list[$v['id']] = "{$v['archives_sn']} {$v['engineering']}";
                $contract_time_list[$v['id']] = date('Y-m-d',$v['address_time']);
                //$contract_time_list[$v['id']] = date('Y-m-d',$v['contract_time']);
            }
        }

        $plan_list = Db::name('mill_order_plan')->where(['order_id'=>$order_id])->order('give_status asc')->select();

        //获取计划环节
        $sort = PlanModel::getPlanSort();

        if(empty($plan_list)){
            $sort[-1] = '下单';//加入主计划单
            ksort($sort);
            foreach ($sort as $sk=>$sv){
                $plan = [
                    //'order_id'          =>  '',
                    //'order_pid'         =>  '',
                    //'archives_sn'       =>  '',
                    'note'              =>  '',
                    'plan_time'         =>  time(),
                    'create_time'       =>  time(),
                    'give_status'       =>  $sk,
                    'title'             =>  $sv,
                    'is_true'           =>  1,
                ];

                $plan_list[] = $plan;
            }
        }

        $order['plan_list'] = $plan_list;

        $table_arr = PlanModel::fromTabale($order);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        $js = '<script type="text/javascript">
                $(function() {
                    var contract_time_list = \''.json_encode($contract_time_list).'\';
                    contract_time_list = $.parseJSON(contract_time_list);
                    
                    $(".plan_time'.$address_status.'").attr("type","hidden");
                    $(".plan_time'.$address_status.'").before("<div class=\'plan_time'.$address_status.'_text\'>"+$(".plan_time'.$address_status.'").attr("value")+"</div>");
                    //名称事件
                    $("body").on("change","select[name=\'order_id\']",function(){
                        var order_id = $(this).val();
                        var help_block = contract_time_list[order_id];
                        
                        $("#order_id").siblings(".help-block").html(help_block);
                        $(".plan_time'.$address_status.'").attr("value",help_block);
                        $(".plan_time'.$address_status.'_text").html(help_block);
                        
                        
                    });
                })
            </script>';

        $info = [];
        $title = '新增排产计划单';

        $addFormItems = [['select:6||||must', 'order_id', '选择批次[:请选择批次]', '发货时间：', $order_list]];
        if(!empty($order_id)){
            $title = '修改排产计划单';
            $order = Db::name('mill_order')->where(['id'=>$order_id])->find();

            $addFormItems = [['static:6||||must', 'static', '工程', '', "{$order['archives_sn']} {$order['engineering']}"]];
        }
        $addFormItems[] = ['complexTable:6', 'contract', '', $table_data, $table_head];
        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addDate('','仅加载时间插件用','', '','','','hidden')
            ->addFormItems($addFormItems)
            ->setExtraJs($js)
            ->setFormData($info)
            ->fetch();


    }

    /**
     * 下单列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function placeList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();

        // 数据列表
        $data_list = Db::name('mill_order_place')
            ->alias('p')
            ->field('p.*')
            ->where($map)
            ->order('p.status asc,p.place_time asc')
            ->paginate()
            ->each(function ($v) {

                //是否可以确认完成
                $v['is_status'] = 0;//默认不可确认
                //如果未确认完成，且已上传的面积表产品数量超过下单预设数量，则可确认完成
                if($v['status'] == 0 && $v['archives_number'] >= $v['number'])$v['is_status'] = 1;

                //发货前的最后一个状态
                $address_status = GiveModel::$role[8]['status'][1];
                //判断最后一次发货时间，是否超过交付时间
                $give_where = [
                    ['o.order_sn_off','=',$v['order_sn_off']],
                    ['g.status','=',$address_status],
                ];
                $v['address_last_time'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->leftJoin('mill_order o','o.id=g.order_id')
                    ->where($give_where)
                    ->order('address_time desc')
                    ->value('address_time');
                $v['address_status'] = $v['address_time'] - $v['address_last_time'];
                if($v['address_status'] < 0)$v['address_status'] = OrderModel::status_tag(-1, '已超期');
                else $v['address_status'] = '';

                //获取该工程所有的制图员、工艺员
                $order_where = [
                    ['order_sn_off','=',$v['order_sn_off']],
                ];
                $order_list = Db::name('mill_order')->where($order_where)->select();
                if(!empty($order_list)){

                    $user_list_html = '<ul class="dch-ul">';
                    foreach ($order_list as $order) {
                        $user_list_html .= "<li class='dch-li'>批次：<span class='tab-text-info'>{$order['batch']}</span> | 制图员：<span class='tab-text-info'>{$order['archives_plan']}</span> | 工艺员：<span class='tab-text-info'>{$order['archives_open']}</span></li>";
                    }
                    $user_list_html .= '</ul>';
                    $v['user_list_html'] = $user_list_html;
                }


                return $v;
            });


        //JS
        $js = '<script type="text/javascript">
                $(function() {
                            
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "下单管理",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('下单管理')// 页面标题
            ->setTableName('mill_order_place')// 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'p.order_sn_off', '订单编号', 'like'],
                ['text:2', 'p.engineering', '工程名称', 'like'],
                ['daterange:2', 'p.plan_time', '工艺下单时间'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn_off', '订单编号','text.edit'],
                ['engineering', '工程名称'],
                ['row_area','面积','text.edit'],
                ['number','数量','text.edit'],
                ['archives_row_area','已完成面积'],
                ['archives_number','已完成数量'],
                ['user_list_html','制图员和工艺员'],
                ['status','状态','callback',function($value, $data){
                    $status_arr = [0=>'未完成',1=>'已完成'];
                    $status = OrderModel::status_tag($value,$status_arr[$value]);
                    return $status;
                },'__data__'],
                ['place_time', '工艺下单时间','date'],
                ['contract_time', '合同交付时间','date.edit'],
                ['address_time', '发货时间','date.edit'],
                ['address_status','交付状态'],
                ['note', '备注','text.edit'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-default quality-print'])
            //->addTopButton('placeAdd',['title' => '新增','href' => url('placeAdd'),'icon'=>'','class'=>'btn btn-primary disable-dch'])
            //->addRightButton('placeAdd',['title' => '修改','href' => url('placeAdd',['id' => '__id__']),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->addRightButton('placeDel',['title' => '删除','href' => url('placeDel',['id' => '__id__']),'class'=>'btn btn-primary disable-dch ajax-get','icon'=>''])
            ->addRightButton('backEnable',['title' => '确认完成','href' => url('placeEnable',['id' => '__id__']).'?fieldv=status|1','class'=>'btn btn-primary disable-dch ajax-get','icon'=>''])
            ->replaceRightButton(['archives_number' => ['<>','0']],'',['placeDel'])
            ->replaceRightButton(['is_status' => ['=','0']],'',['backEnable'])
            ->setRowList($data_list)// 设置表格数据
            ->setColumnWidth([
                'id' => 60,
                'order_sn_off' => 120,
                'engineering' => 150,
                'user_list_html' => 250,
                'row_area' => 90,
                'number' => 80,
                'archives_row_area' => 90,
                'archives_number' => 85,
                'status' => 70,
                'note' => 100,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 下单新增
     * @return mixed
     */
    public function placeAdd()
    {
        $order_pid = input('order_pid');
        if(empty($order_pid))$this->error('请选择工程');

        if ($this->request->isPost()) {
            $data = input();

            $id = $data['id'];
            unset($data['id']);

            if (empty($data['number'])) $this->error('请填写数量');
            if (empty($data['order_sn_off'])) $this->error('请填写订单编号');

            $data['place_time'] = strtotime($data['place_time']);
            $data['contract_time'] = strtotime($data['contract_time']);
            $data['address_time'] = strtotime($data['address_time']);

            if(empty($id)){
                //判断订单编号是否重复
                $order_sn_off_count = Db::name('mill_order_place')->where(['order_sn_off'=>$data['order_sn_off']])->count();
                if($order_sn_off_count)$this->error('该订单编号已存在');
                $data['create_time'] = time();
                Db::name('mill_order_place')->insert($data);
            }
            else Db::name('mill_order_place')->where(['order_pid'=>$order_pid])->update($data);

            $this->success('操作成功', cookie('__forward__'));
        }

        $order = Db::name('mill_order')->where(['order_pid'=>$order_pid])->find();
        //$info = Db::name('mill_order_place')->where(['order_pid'=>$order_pid])->find();
        $info = [];
        if(empty($info)){
            $info['order_pid'] = $order['order_pid'];
            $info['engineering'] = $order['engineering'];
            $info['order_sn'] = $order['order_sn'];
            $info['place_time'] = time();
            $info['contract_time'] = time();
            $info['address_time'] = time();
        }
        $info['title'] = "{$info['order_sn']}  {$info['engineering']}";


        return ZBuilder::make('form')
            ->setPageTitle('下单') // 页面标题
            ->addHidden('id')
            ->addHidden('order_pid')
            ->addHidden('order_sn')
            ->addHidden('engineering')
            ->addFormItems([ // 批量添加表单项
                ['static', 'title', '工程'],
                ['number:||||must', 'number', '数量'],
                ['text', 'row_area', '面积'],
                ['text:||||must', 'order_sn_off', '订单编号'],
                ['date:||||must', 'place_time', '工艺下单时间'],
                ['date:||||must', 'contract_time', '合同交付时间'],
                ['date:||||must', 'address_time', '发货时间'],
                ['textarea', 'note', '备注'],
            ])
            ->setFormData($info)
            ->fetch();


    }

    /**
     * 下单删除
     * @return mixed
     */
    public function placeDel()
    {
        $id = input('id');

        $info = Db::name('mill_order_place')->where(['id'=>$id])->find();

        if(empty($info))$this->error('该单子不存在');
        if($info['archives_number'] > 0)$this->error('该单子已有面积表,不支持删除');

        Db::name('mill_order_place')->where(['id'=>$id])->delete();

        $this->success('删除成功');

    }

    /**
     * 下单确认完成
     * @return mixed
     */
    public function placeEnable()
    {
        $ids = input('ids');
        $id = input('id');
        if($id)$ids[] = $id;
        if(empty($ids))$this->error('请选择工程');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);

        foreach ($ids as $id){

            $add = [
                $fieldv[0]              =>  $fieldv[1],
                $fieldv[0].'_time'      =>  time(),
            ];
            Db::name('mill_order_place')->where(['id'=>$id])->update($add);
        }

        $this->success('提交成功', null, '_parent_reload');

    }

    /**
     * 开平管理列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function cuttingList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        //$map[] = ['status','in','0,-1'];
        $map[] = $map0[] = $map01[] = ['o.archives_status','in','2'];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.id as order_id,d.id as id,client_id as client_id2,d.id as drawing_id,d.waiback_drawing,d.cutting_batch')
            ->leftJoin('mill_order_archives_cutting_drawing d','o.id=d.order_id')
            ->where($map)
            ->group('o.id,d.id')
            ->order('o.status asc,d.id desc,o.id desc')
            ->paginate()
            ->each(function ($v){

                if(empty($v['drawing_id']))$v['drawing_id'] = 0;
                if(empty($v['waiback_drawing']))$v['waiback_drawing'] = '';
                $v['number_sum'] = Db::name('mill_order_archives_cutting')->where(['drawing_id'=>$v['drawing_id'],'is_main'=>1])->sum('number');

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".drawing_btn").css("display","none");
                    $(".waiback_drawing").click(function(){
                        $(this).parents("tr").find("[data-files='."'".'drawing'."'".']").click();
                    })
                });
            </script>';

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('开料表管理') // 页面标题
            ->setTableName('mill_order_archives_cutting_drawing') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                //['back_status_time', '合同签订日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['cutting_batch', '开料批次'],
                ['number_sum','产品总量'],
                ['waiback_drawing','开料表','files.edit'],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraJs($js)
            //->addRightButton('enable',['title' => '审核通过'])
            //->addRightButton('enable',['title' => '审核通过','href' => url('urgent',['id' => '__id__']),'icon'=>''],['area' => ['1200px', '80%'], 'title' => ['审核通过', 'font-size:24px;text-align: center;']])
            ->addRightButton('cuttingShow',['title' => '开平详情','href' => url('cuttingShow',['order_id' => '__order_id__','drawing_id' => '__drawing_id__']),'class'=>'btn btn- btn-default','icon'=>''])
            ->addRightButton('drawingAdd',['title' => '新增','href' => url('drawing',['order_id' => '__order_id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['780px', '50%'], 'title' => ['新增开料表', 'font-size:24px;text-align: center;']])
            ->addRightButton('drawing',['title' => '上传开料表','href' => url('drawing',['id' => '__drawing_id__','order_id' => '__order_id__']),'icon'=>'','class'=>'btn btn-default disable-dch drawing_btn','data-files'=>'drawing'],['area' => ['780px', '50%'], 'title' => ['选择开料表', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['drawing_id' => ['=','0']],'',['drawingAdd'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 上传开料表图纸
     */
    public function drawing()
    {
        $id = input('id');
        $order_id = input('order_id');

        // 获取订单信息
        $info = Db::name('mill_order')->where(['id'=>$order_id])->find();
        if(!empty($id))$info['waiback_drawing'] = Db::name('mill_order_archives_cutting_drawing')->where(['id'=>$id])->value('waiback_drawing');

        if ($this->request->isPost()) {

            $data = input();

            $add = [
                'order_id'          =>  $info['id'],
                'order_pid'         =>  $info['order_pid'],
                'archives_sn'       =>  $info['archives_sn'],
                'waiback_drawing'   =>  $data['waiback_drawing'],
            ];
            //新增开料表图纸信息
            $add_id = '';
            $info['is_add'] = 0;
            if(empty($id)){
                $add['create_time'] = time();
                $add_id = Db::name('mill_order_archives_cutting_drawing')->insertGetId($add);
                $info['is_add'] = 1;
            }

            // 加入开料表图纸信息
            $info['drawing_id'] = empty($id)?$add_id:$id;
            $info['waiback_drawing'] = $add['waiback_drawing'];

            //更新开料面积表数据
            $msg = ArchivesModel::updateArchivesCutting($info);
            if(!empty($msg)){
                if(!empty($add_id))Db::name('mill_order_archives_cutting_drawing')->where(['id'=>$add_id])->delete();
                $this->error($msg);
            }
            elseif ($id)Db::name('mill_order_archives_cutting_drawing')->where(['id'=>$id])->update($add);


            $this->success('操作成功', null, '_parent_reload');
        }

        //$info['info_str'] = empty($info['archives_sn'])?'无档案号':$info['archives_sn'];
        $info['info_str'] = "{$info['engineering']} {$info['archives_sn']}";

        return ZBuilder::make('form')
            ->setPageTitle('上传开料表') // 页面标题
            //->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['static:12', 'info_str', ''],
                ['file:12', 'waiback_drawing', '请上传开料表'],
            ])
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 开平管理
     * @return mixed
     */
    public function cuttingShow()
    {
        $drawing_id = input('drawing_id');
        $order_id = input('order_id');
        $cutting_log_sn = input('cutting_log_sn');//开平单号
        $is_cutting = input('is_cutting',0);//开始生产
        $stock_sn = input('stock_sn');//铝卷编号

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        $map[] = ['is_main','=',1];
        $map[] = $map0[] = $map01[] = ['drawing_id','=',$drawing_id];

        if(!empty($cutting_log_sn))$map[] = ['status','=',0];

        //获取铝卷信息
        $stock = Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->find();
        if(!empty($stock['quality']))$quality = Db::name('wh_supplier_quality')->where(['id'=>$stock['quality']])->value(['title']);
        else $quality = '';

        // 数据列表
        $data_list = Db::name('mill_order_archives_cutting')
            ->field("*,'{$is_cutting}' as is_cutting")
            ->where($map)
            //->order('cutting_sn asc,is_main desc,cutting_sort asc,sort desc')
            ->order('cutting_sort asc')
            ->select();

        if(!empty($data_list)){
            foreach ($data_list as &$v){

                //材质
                $v['plank'] = $quality;

                if(!empty($cutting_log_sn)){
                    //剩余开平数量
                    $number = Db::name('mill_order_archives_cutting_log')->where(['cutting_id'=>$v['id']])->sum('cutting_number');
                    $v['number'] = $v['number'] - intval($number);
                    //剩余面积
                    $v['row_area'] = $v['one_area']*$v['number'];
                    //剩余重量
                    $v['row_num'] = $v['num']*$v['number'];
                }
            }
        }

        //获取工程
        $order = Db::name('mill_order')->where(['id'=>$order_id])->find();

        //开平单详情
        $log_body_arr = [];

        $title = $title2 = "{$order['engineering']} {$order['order_sn']}  {$order['batch']}";

        $SearchArea = [['select:2', 'status', '状态','','',[0=>'待开平',1=>'已开平']]];
        $ablequality = ['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print'];
        if(!empty($cutting_log_sn)){
            $title = "开平单号（{$cutting_log_sn}）：{$title}";

            $SearchArea = '';
            $ablequality = ['title' => '打印开平单','class'=>'btn btn-success','href' => url('cuttingLogShow',['cutting_log_sn' => $cutting_log_sn,'is_print'=>2]),'icon'=>''];


            //获取开平单详情
            $log_body_arr = Db::name('mill_order_archives_cutting_log')
                ->alias('l')
                ->field("l.*,concat(o.engineering,' ',o.archives_sn) as engineering")
                ->leftJoin('mill_order o','o.id=l.order_id')
                ->where([['l.cutting_log_sn','=',$cutting_log_sn]])
                ->order('l.cutting_log_time desc')
                ->select();
        }
        else $title = "开平详情：{$title}";

        //开平单表格
        $log_head_arr = [
            ['engineering', '工程'],
            ['cutting_sort', '开平序号'],
            ['sort', '面积表序号'],
            ['plank', '材质'],
            ['thickness', '板厚(mm)'],
            ['high', '宽度(mm)'],
            ['long', '长度(mm)'],
            ['number', '开平数量(片)'],
            ['long_hs', '开平长度(M)'],
            ['row_area', '面积(m²)'],
            ['row_num', '重量(kg)'],
            ['cutting_sn', '备注'],
            ['note', '工艺']
        ];

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    //是否开始生产
                    var cutting_log_sn = "'.$cutting_log_sn.'";
                    
                    if(cutting_log_sn){
                        //隐藏按钮
                        $(".cuttingEnable").remove();
                        
                    }
                    else{
                        //隐藏按钮
                        $(".cuttingSub").remove();
                        $(".cuttingLogShow").remove();
                    }
                    
                    //导出
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order_archives_cutting') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea($SearchArea)
            ->addColumns([ // 批量添加列
                //['sort', '序号'],
                //['page', '图号'],
                //['model_sn', '编号'],
                //['thickness', '板厚'],
                //['high2', '开料-H(mm)'],
                //['long2', '开料-L(mm)'],
                //['number2', '数量'],
                //['high', '用料-H(mm)'],
                //['long', '用料-L(mm)'],
                //['number', '用料数量'],
                //['cutting_sn', '套料'],
                //['note', '工艺'],
                ['cutting_sort', '开平序号'],
                ['sort', '面积表序号'],
                ['plank', '材质'],
                ['thickness', '板厚(mm)'],
                ['high', '宽度(mm)'],
                ['long', '长度(mm)'],
                ['number', '开平数量(片)'],
                ['long_hs', '开平长度(M)'],
                ['row_area', '面积(m²)'],
                ['row_num', '重量(kg)'],
                ['cutting_sn', '备注'],
                ['note', '工艺'],
                ['status','状态','callback',function($value, $data){
                    $status_arr = [0=>'待开平',1=>'已开平'];
                    $status = OrderModel::status_tag($value,$status_arr[$value]);
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            //->addTopButton('cuttingSub',['title' => '完成开平','href' => url('cuttingEnable',['cutting_log_sn'=>$cutting_log_sn,'is_sub'=>1]),'class'=>'btn btn- btn-primary ajax-get cuttingSub','icon'=>''])
            ->addTopButton('cuttingLogShow',['title' => '开平单详情','class'=>'btn btn-primary cuttingSub','href' => url('cuttingLogShow',['cutting_log_sn'=>$cutting_log_sn,'order_id'=>$order_id,'is_cutting'=>1]),'icon'=>''],['area' => ['90%', '90%'], 'title' => ["开平单详情", 'font-size:24px;text-align: center;']])
            ->addTopButton('cuttingSub',['title' => '完成开平','class'=>'btn btn-primary cuttingSub','href' => url('cuttingEnable',['cutting_log_sn'=>$cutting_log_sn,'is_sub'=>1]),'icon'=>''],['area' => ['90%', '90%'], 'title' => ["打印中。。。", 'font-size:24px;text-align: center;']])
            ->addTopButton('ablequality',$ablequality)
            ->addTopButton('cuttingEnable',['title' => '开始生产','class'=>'btn btn-primary cuttingEnable','href' => url('cuttingEnable',['order_id' => $order_id,'drawing_id' => $drawing_id]),'icon'=>''],['area' => ['780px', '780px'], 'title' => ["开始生产：{$title2}", 'font-size:24px;text-align: center;']])
            ->addRightButton('enable',['title' => '确认','href' => url('cuttingEnable',['id' => '__id__','order_id' => '__order_id__','drawing_id'=>$drawing_id,'cutting_log_sn'=>$cutting_log_sn,'stock_sn'=>$stock_sn]),'class'=>'btn btn- btn-primary','icon'=>''],['area' => ['900px', '480px'], 'title' => ["确认", 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['=', '1']], '', 'enable')
            ->replaceRightButton(['is_cutting' => ['=', '0']], '', 'enable')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板


    }
    public function cuttingShow_old()
    {
        $drawing_id = input('drawing_id');
        $order_id = input('order_id');
        $cutting_log_sn = input('cutting_log_sn');//开平单号
        $is_cutting = input('is_cutting',0);//开始生产
        $stock_sn = input('stock_sn');//铝卷编号

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        $map[] = ['is_main','=',1];
        $map[] = $map0[] = $map01[] = ['drawing_id','=',$drawing_id];

        if(!empty($cutting_log_sn))$map[] = ['status','=',0];

        //获取铝卷信息
        $stock = Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->find();
        if(!empty($stock['quality']))$quality = Db::name('wh_supplier_quality')->where(['id'=>$stock['quality']])->value(['title']);
        else $quality = '';

        // 数据列表
        $data_list = Db::name('mill_order_archives_cutting')
            ->field("*,'{$is_cutting}' as is_cutting")
            ->where($map)
            //->order('cutting_sn asc,is_main desc,cutting_sort asc,sort desc')
            ->order('cutting_sort asc')
            ->select();

        if(!empty($data_list)){
            foreach ($data_list as &$v){

                //材质
                $v['plank'] = $quality;

                if(!empty($cutting_log_sn)){
                    //剩余开平数量
                    $number = Db::name('mill_order_archives_cutting_log')->where(['cutting_id'=>$v['id']])->sum('cutting_number');
                    $v['number'] = $v['number'] - intval($number);
                    //剩余面积
                    $v['row_area'] = $v['one_area']*$v['number'];
                    //剩余重量
                    $v['row_num'] = $v['num']*$v['number'];
                }
            }
        }

        //获取工程
        $order = Db::name('mill_order')->where(['id'=>$order_id])->find();

        //开平单详情
        $log_body_arr = [];

        $title = $title2 = "{$order['engineering']} {$order['order_sn']}  {$order['batch']}";

        $SearchArea = [['select:2', 'status', '状态','','',[0=>'待开平',1=>'已开平']]];
        $ablequality = ['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print'];
        if(!empty($cutting_log_sn)){
            $title = "开平单号（{$cutting_log_sn}）：{$title}";

            $SearchArea = '';
            $ablequality = ['title' => '打印开平单','class'=>'btn btn-success','href' => url('cuttingLogShow',['cutting_log_sn' => $cutting_log_sn,'is_print'=>2]),'icon'=>''];


            //获取开平单详情
            $log_body_arr = Db::name('mill_order_archives_cutting_log')
                ->alias('l')
                ->field("l.*,concat(o.engineering,' ',o.archives_sn) as engineering")
                ->leftJoin('mill_order o','o.id=l.order_id')
                ->where([['l.cutting_log_sn','=',$cutting_log_sn]])
                ->order('l.cutting_log_time desc')
                ->select();
        }
        else $title = "开平详情：{$title}";

        //开平单表格
        $log_head_arr = [
            ['engineering', '工程'],
            ['cutting_sort', '序号'],
            ['plank', '材质'],
            ['thickness', '板厚(mm)'],
            ['high', '宽度(mm)'],
            ['long', '长度(mm)'],
            ['number', '开平数量(片)'],
            ['long_hs', '开平长度(M)'],
            ['row_area', '面积(m²)'],
            ['row_num', '重量(kg)'],
            ['cutting_sn', '备注'],
            ['note', '工艺']
        ];

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    //是否开始生产
                    var cutting_log_sn = "'.$cutting_log_sn.'";
                    
                    if(cutting_log_sn){
                        //隐藏按钮
                        $(".cuttingEnable").remove();
                        //重置表格高度
                        var table_body_height = $("#builder-table-body").height()/2;
                        $("#builder-table-body").css("max-height",table_body_height+"px");
                        
                        //组装表头
                        var table2_head_arr = '.json_encode($log_head_arr,JSON_UNESCAPED_UNICODE).';
                        var table2_head = "";
                        var table2_head_col = "";
                        $.each(table2_head_arr,function(i,j){
                            //组装表头
                            table2_head += "<th>"+j[1]+"</th>";
                            table2_head_col += "<col width=\'100\'>";
                        });
                        var table2_head_html = \'<div class="builder-table-head" ><table class="table table-builder table-hover table-bordered table-striped" "><colgroup>\'+table2_head_col+\'</colgroup><thead><tr>\'+table2_head+\'</tr></thead></table></div>\';
                        
                        //组装表体
                        var table2_body_arr = '.json_encode($log_body_arr,JSON_UNESCAPED_UNICODE).';
                        var table2_body = "";
                        if(table2_body_arr){
                            $.each(table2_body_arr,function(n,m){
                                //组装表体
                                table2_body += "<tr>";
                                $.each(table2_head_arr,function(i,j){
                                    table2_body += "<td>"+m[j[0]]+"</td>";
                                });
                                table2_body += "</tr>";
                            });
                        }
                        var table2_body_html = \'<div class="builder-table-body" style="max-height: \'+table_body_height+\'px;"><table class="table table-builder table-hover table-bordered table-striped"><colgroup>\'+table2_head_col+\'</colgroup><tbody><tr>\'+table2_body+\'</tr></tbody></table></div>\';
                        
                        var table2_html = \'<div class="block"><div class="block-content tab-content"><div class="tab-pane active">\' +
                         table2_head_html+
                         table2_body_html+
                         \'</div></div></div>\';
                        //展示开平单
                        $(".tab-content").parent().parent().append(table2_html);
                        
                    }
                    else{
                        //隐藏按钮
                        $(".cuttingSub").remove();
                    }
                    
                    //导出
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order_archives_cutting') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea($SearchArea)
            ->addColumns([ // 批量添加列
                //['sort', '序号'],
                //['page', '图号'],
                //['model_sn', '编号'],
                //['thickness', '板厚'],
                //['high2', '开料-H(mm)'],
                //['long2', '开料-L(mm)'],
                //['number2', '数量'],
                //['high', '用料-H(mm)'],
                //['long', '用料-L(mm)'],
                //['number', '用料数量'],
                //['cutting_sn', '套料'],
                //['note', '工艺'],
                ['cutting_sort', '序号'],
                ['plank', '材质'],
                ['thickness', '板厚(mm)'],
                ['high', '宽度(mm)'],
                ['long', '长度(mm)'],
                ['number', '开平数量(片)'],
                ['long_hs', '开平长度(M)'],
                ['row_area', '面积(m²)'],
                ['row_num', '重量(kg)'],
                ['cutting_sn', '备注'],
                ['note', '工艺'],
                ['status','状态','callback',function($value, $data){
                    $status_arr = [0=>'待开平',1=>'已开平'];
                    $status = OrderModel::status_tag($value,$status_arr[$value]);
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            //->addTopButton('cuttingSub',['title' => '完成开平','href' => url('cuttingEnable',['cutting_log_sn'=>$cutting_log_sn,'is_sub'=>1]),'class'=>'btn btn- btn-primary ajax-get cuttingSub','icon'=>''])
            ->addTopButton('cuttingSub',['title' => '完成开平','class'=>'btn btn-primary cuttingSub','href' => url('cuttingEnable',['cutting_log_sn'=>$cutting_log_sn,'is_sub'=>1]),'icon'=>''],['area' => ['90%', '90%'], 'title' => ["打印中。。。", 'font-size:24px;text-align: center;']])
            ->addTopButton('ablequality',$ablequality)
            ->addTopButton('cuttingEnable',['title' => '开始生产','class'=>'btn btn-primary cuttingEnable','href' => url('cuttingEnable',['order_id' => $order_id,'drawing_id' => $drawing_id]),'icon'=>''],['area' => ['780px', '780px'], 'title' => ["开始生产：{$title2}", 'font-size:24px;text-align: center;']])
            ->addRightButton('enable',['title' => '确认','href' => url('cuttingEnable',['id' => '__id__','order_id' => '__order_id__','drawing_id'=>$drawing_id,'cutting_log_sn'=>$cutting_log_sn,'stock_sn'=>$stock_sn]),'class'=>'btn btn- btn-primary','icon'=>''],['area' => ['900px', '480px'], 'title' => ["确认", 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['=', '1']], '', 'enable')
            ->replaceRightButton(['is_cutting' => ['=', '0']], '', 'enable')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板


    }

    /**
     * 开平管理确认
     * @return mixed
     */
    public function cuttingEnable()
    {
        $id = input('id');//开平产品ID
        $drawing_id = input('drawing_id');//开料表图纸ID
        $order_id = input('order_id');//工程ID
        $cutting_log_sn = input('cutting_log_sn');//开平编号
        $stock_sn = input('stock_sn2',input('stock_sn'));//铝卷编号
        $is_sub = input('is_sub');//确认完成

        //开平确认完成，并自动打印开平单
        if($is_sub){

            Db::name('mill_order_archives_cutting_log')->where(['cutting_log_sn'=>$cutting_log_sn])->update(['status'=>2]);

            exit("<script type='text/javascript'>window.location.href='".url('cuttingLogShow',['cutting_log_sn' => $cutting_log_sn,'is_print'=>2])."'</script>';");
        }

        //确认生产信息，并开始开平生产
        if ($this->request->isPost()) {
            if(empty($cutting_log_sn))$this->error('请选择生产编号');
            if(empty($stock_sn))$this->error('请选择铝卷');

            //如果开平产品ID存在，则为确认开平，并记录至生产编号
            if(!empty($id)){
                $cutting_number = input('cutting_number');
                if(empty($cutting_number))$this->error('请输入数量');

                $cutting = Db::name('mill_order_archives_cutting')->where(['id'=>$id])->find();
                if(empty($cutting))$this->error('该产品不存在');

                //获取铝卷信息
                $stock = Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->find();
                $stock['quality'] = Db::name('wh_supplier_quality')->where(['id'=>$stock['quality']])->value(['title']);

                $add = $cutting;
                unset($add['id']);

                $add['uid'] = UID;
                $add['status'] = 1;
                $add['cutting_id'] = $cutting['id'];
                $add['cutting_log_sn'] = $cutting_log_sn;
                $add['cutting_log_time'] = time();
                $add['cutting_number'] = $cutting_number;
                //铝卷信息
                $add['stock_sn'] = $stock['stock_sn'];
                $add['lot_sn'] = $stock['lot_sn'];
                $add['thickness3'] = $stock['thickness'];
                $add['plank'] = $stock['quality'];
                $add['high3'] = $stock['high'];
                $add['long3'] = $cutting['long'];

                //新增开平记录
                Db::name('mill_order_archives_cutting_log')->insert($add);

                //根据套料更新信息
                $count = Db::name('mill_order_archives_cutting_log')->where(['cutting_id'=>$cutting['id']])->sum('cutting_number');
                if($count >= $cutting['number'])Db::name('mill_order_archives_cutting')->where(['cutting_sn'=>$cutting['cutting_sn']])->update(['status'=>1]);

                //获取已开平数量，和总数量
                //总数量
                $cutting_count = Db::name('mill_order_archives_cutting')->where(['order_id'=>$add['order_id'],'is_main'=>1])->sum('number');
                //已开平数量
                $cutting_log_count = Db::name('mill_order_archives_cutting')->where(['order_id'=>$add['order_id'],'is_main'=>1,'status'=>1])->sum('number');

                //更新排产计划单
                $end_time = 0;
                if($cutting_count == $cutting_log_count)$end_time = time();
                $order = Db::name('mill_order')->where(['id'=>$add['order_id']])->find();
                PlanModel::updatePlan($order,0,0,time(),$end_time);

                //$this->success('操作成功','','_parent_reload');

            }
            $this->success('操作成功',url('cuttingShow',['order_id'=>$order_id,'drawing_id'=>$drawing_id,'is_cutting'=>1,'cutting_log_sn'=>$cutting_log_sn,'stock_sn'=>$stock_sn]),'_parent_reload');
        }

        //工程信息
        $info = Db::name('mill_order')->where(['id'=>$order_id])->find();
        //设置开料单号
        $cutting_log_sn_list = [];
        if(empty($id)){
            $info['cutting_log_sn'] = GiveModel::getCuttingLogSn();
            $cutting_log_sn_list[$info['cutting_log_sn']] = "{$info['cutting_log_sn']}（新单号）";
        }

        $title = "{$info['engineering']} {$info['order_sn']}  {$info['batch']}";

        //加入未完成生产的开料单号
        $cutting_log_list = Db::name('mill_order_archives_cutting_log')->field('group_concat(DISTINCT archives_sn) as archives_sn,cutting_log_sn')->where([['status','<',2]])->group('cutting_log_sn')->order('cutting_log_sn desc')->select();
        if(!empty($cutting_log_list)){
            foreach ($cutting_log_list as $v){
                $cutting_log_sn_list[$v['cutting_log_sn']] = "{$v['cutting_log_sn']}（{$v['archives_sn']}）";
            }
        }
        //获取铝卷
        $stock_sn_list = Db::name('wh_stock')
            ->alias('s')
            //->field('s.*,tt.title as type_name')
            ->leftJoin('wh_stock_type tt','tt.id=s.type_id')
            ->where(['s.type_pid'=>4])
            ->order('s.model asc')
            ->column("concat(tt.title,' —— 厚：',s.thickness,' —— 宽：',s.model,' —— 卷号：',lot_sn,'')",'s.stock_sn');


        //确认开始生产
        $addFormItems = [ // 批量添加表单项
            ['static:12', 'title', '工程'],
            ['select:12', 'cutting_log_sn', '生产编号','',$cutting_log_sn_list],
            ['select:12', 'stock_sn', '选择铝卷','',$stock_sn_list],
        ];
        //生产记录
        if(!empty($id)){
            $info = Db::name('mill_order_archives_cutting')->where(['id'=>$id])->find();
            if(empty($info))$this->error('该产品不存在');
            if($info['status'] != 0)$this->error('该产品已开平');
            $info['cutting_log_sn'] = $cutting_log_sn;
            $info['stock_sn2'] = $stock_sn;

            //获取剩余数量
            $info['cutting_number'] = Db::name('mill_order_archives_cutting_log')->where(['cutting_id'=>$id])->sum('cutting_number');
            $info['cutting_number'] = $info['number'] - intval($info['cutting_number']);
            if($info['cutting_number'] == 0)$this->error('该产品已开平');

            $addFormItems = [ // 批量添加表单项
                ['static:6', 'cutting_log_sn', '生产编号：'],
                ['static:6', 'title', '工程：'],
                ['static:3', 'cutting_sort', '序号：'],
                ['static:3', 'thickness', '板厚：'],
                ['static:3', 'high', '宽度：'],
                ['static:3', 'long', '长度：'],
                ['select:12', 'stock_sn2', '铝卷','',$stock_sn_list],
                ['number:12', 'cutting_number', '数量'],
            ];
        }

        $info['title'] = $title;

        return ZBuilder::make('form')
            ->setPageTitle('确认生产') // 页面标题
            ->addFormItems($addFormItems)
            ->setFormData($info)
            ->layout(['note'=>12])
            ->fetch();


    }

    /**
     * 开平单列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function cuttingLogList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        // 数据列表
        $data_list = Db::name('mill_order_archives_cutting_log')
            ->alias('l')
            ->field('l.*,o.engineering,o.batch')
            ->leftJoin('mill_order o','o.id=l.order_id')
            ->where($map)
            ->group('cutting_log_sn')
            ->order('cutting_log_time desc')
            ->paginate()
            ->each(function ($v){

                $v['number_sum'] = Db::name('mill_order_archives_cutting_log')->where(['cutting_log_sn'=>$v['cutting_log_sn']])->sum('cutting_number');

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('开平单管理') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'l.cutting_log_time', '时间'],
                //['select:2', 'status', '审核状态','','',[0=>'待审核',1=>'已审核',-1=>'未通过']],
            ])
            ->addColumns([ // 批量添加列
                //['back_status_time', '合同签订日期','date'],
                ['cutting_log_sn', '开平单号'],
                ['archives_sn', '档案号'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum','开平总数量'],
                ['cutting_log_time', '开平时间','date'],
                ['right_button', '操作', 'btn']
            ])
            ->setRowList($data_list) // 设置表格数据
            ->addRightButton('cuttingLogShow',['title' => '详情','href' => url('cuttingLogShow',['cutting_log_sn' => '__cutting_log_sn__']),'class'=>'btn btn- btn-default','icon'=>''])
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 开平单详情
     * @return mixed
     */
    public function cuttingLogShow()
    {
        $cutting_log_sn = input('cutting_log_sn');//开平单号
        $is_print = input('is_print');//是否导出开平单
        $is_cutting = input('is_cutting');//是否正在开平中
        $order_id = input('order_id ');//开平中的订单编号

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();

        $map['cutting_log_sn'] = $cutting_log_sn;

        // 数据列表
        $data_list = Db::name('mill_order_archives_cutting_log')
            ->field("*")
            ->where($map)
            //->order('cutting_sn asc,is_main desc,cutting_sort asc,sort desc')
            ->order('cutting_log_time desc')
            ->select();

        if(!empty($data_list)){
            //获取工程
            $order = Db::name('mill_order')->where(['id'=>$data_list[0]['order_id']])->find();
            $title = "开平单（{$cutting_log_sn}）：{$order['engineering']} {$order['order_sn']}  {$order['batch']}";
        }
        else{
            $title = '开平单';
        }

        //打印
        if($is_print == 2){
            $field = [
                'cutting_sort'          =>  '开平序号',
                'sort'                  =>  '面积表序号',
                'plank'                 =>  '材质',
                'thickness'             =>  '板厚(mm)',
                'high'                  =>  '宽度(mm)',
                'long'                  =>  '长度(mm)',
                'number'                =>  '开平数量(片)',
                'long_hs'               =>  '开平长度(M)',
                'row_area'              =>  '面积(m²)',
                'row_num'               =>  '重量(kg)',
                'cutting_sn'            =>  '备注',
                'note'                  =>  '工艺',
                'thickness3'            =>  '铝卷厚度',
                'log_sn'                =>  '铝卷批号',
            ];
            if(!empty($data_list)){
                $head = "<tr><th colspan='".count($field)."'>{$title}</th></tr>";
                $thead = '';
                $tbody = '';
                foreach ($data_list as $k=>$v){
                    $td = '';
                    foreach ($field as $fk=>$fv){
                        if($k == 0)$thead .= "<th>{$fv}</th>";
                        $td .= "<td>{$v[$fk]}</td>";
                    }
                    $tbody .= "<tr>{$td}</tr>";
                }
                $html = "<table border=\"1\" style=\"text-align: center;border-collapse: collapse;transform-origin: 0 0;\"><thead>{$head}<tr>{$thead}</tr></thead><tbody>{$tbody}</tbody></table>";

                $html .= '
                    <script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script>
                    <script type="text/javascript">
                        window.print();
                    </script>';
                exit($html);
            }
        }

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    //打印标签点击事件
                    $(".archivesPrint").click(function() {
                        $(this).css("display","none");
                        var html = "<span class=\'label label-success\'>已打印</span>";
                        $(this).parents("tr").find(".quality_repair").parents(".table-cell").html(html);
                    });
                    //导出
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                    var is_print = "'.$is_print.'";
                    if(is_print == 1){
                        //$("[data-action=\'fullscreen_toggle\']").click();
                        $(".quality-print").click();
                    }
                })
            </script>';

        if($is_cutting == 1){
            // 使用ZBuilder快速创建数据表格
            return ZBuilder::make('table')
                ->setPageTitle($title) // 页面标题
                ->setTableName('mill_order_archives_cutting_log') // 设置表名
                ->hideCheckbox(true)
                ->addColumns([ // 批量添加列
                    ['cutting_sort', '开平序号'],
                    ['sort', '面积表序号'],
                    ['plank', '材质'],
                    ['thickness', '板厚(mm)'],
                    ['high', '宽度(mm)'],
                    ['long', '长度(mm)'],
                    ['number', '开平数量(片)'],
                    ['long_hs', '开平长度(M)'],
                    ['row_area', '面积(m²)'],
                    ['row_num', '重量(kg)'],
                    ['cutting_sn', '备注'],
                    ['note', '工艺'],
                    ['thickness3', '铝卷厚度'],
                    ['log_sn', '铝卷批号'],
                ])
                ->setRowList($data_list) // 设置表格数据
                ->setColumnWidth([
                    'id'  => 60,
                    'note'  => 100,
                    'mobile'  => 100,
                    'engineering'  => 150,
                    'batch'  => 60,
                ])
                ->fetch(); // 渲染模板
        }
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order_archives_cutting_log') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                //['daterange:2', 'back_status_time', '合同签订日期'],
                //['select:2', 'status', '状态','','',[0=>'待生产',1=>'已生产']],
            ])
            ->addColumns([ // 批量添加列
                ['cutting_sort', '开平序号'],
                ['sort', '面积表序号'],
                ['plank', '材质'],
                ['thickness', '板厚(mm)'],
                ['high', '宽度(mm)'],
                ['long', '长度(mm)'],
                ['number', '开平数量(片)'],
                ['long_hs', '开平长度(M)'],
                ['row_area', '面积(m²)'],
                ['row_num', '重量(kg)'],
                ['cutting_sn', '备注'],
                ['note', '工艺'],
                ['thickness3', '铝卷厚度'],
                ['log_sn', '铝卷批号'],
                ['quality_repair','打印状态','callback',function($value, $data){
                    $text = "<ii class='quality_repair'>".GiveModel::$quality_repair[$value]."</ii>";
                    $status = OrderModel::status_tag($value,$text);
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print'])
            ->addRightButton('archivesPrint',['title' => '打印标签','href' => url('archivesPrint',['cutting_log_id' => '__id__']),'class'=>'btn btn-primary disable-dch archivesPrint','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['quality_repair' => ['<>', '0']], '', 'archivesPrint')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板


    }

    /**
     * 开平单详情
     * @return mixed
     */
    public function archivesPrint()
    {
        $cutting_log_id = input('cutting_log_id');//开平单号

        $cutting_log = Db::name('mill_order_archives_cutting_log')->where(['id'=>$cutting_log_id])->find();
        if(empty($cutting_log))$this->error('该产品不存在');
        //更新产品明细
        ArchivesModel::checkGive($cutting_log['order_id']);

        //获取需要打印的give_id
        $give_ids = '';
        $archives_list = Db::name('mill_order_archives_cutting_log')->field('order_id,sort,cutting_number')->where([['cutting_sn','=',$cutting_log['cutting_sn']],['sort','<>',""]])->order('sort asc')->select();
        if(!empty($archives_list)){
            foreach ($archives_list as $archives){

                //根据开平单数量，获取未打印的指定数量的give_id
                $cutting_number = $archives['cutting_number'];
                $archives = Db::name('mill_order_archives')->where(['order_id'=>$archives['order_id'],'sort'=>$archives['sort']])->find();
                if(!empty($archives)){
                    $where = [
                        ['archives_id','=',$archives['id']],
                        ['quality_repair','=',0],
                    ];
                    $give_id = Db::name('mill_order_archives_give')->where($where)->order('give_sn asc')->limit($cutting_number)->column('id');
                    if(!empty($give_id))$give_ids .= ",".implode(',',$give_id);
                }

            }
        }

        $action = new Give();

        if(!empty($give_ids)){
            //更新打印状态
            Db::name('mill_order_archives_cutting_log')->where(['id'=>$cutting_log_id])->update(['quality_repair'=>2,'quality_time'=>time()]);
            $action->archivesPrint($give_ids);
        }

        $this->error('标签已全部打印');

    }

}